﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OF.Component
{
    public delegate Hashtable MapParameterHandler();

    /// <summary>
    /// 分页查询结果条件实体
    /// </summary>
    [Serializable]
    public class BasePagingSearchCondition 
    {
        public int TotalRecord { get; set; }

        /// <summary>
        ///系统内部传递数据使用 
        /// </summary>
        public string CountMode { get; set; }

        /// <summary>
        /// 页号
        /// </summary>
        public int PageIndex { get; set; }

        /// <summary>
        /// 页面大小
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 排序字段=排序类型列表
        /// </summary>
        public IDictionary<string, ESortType> SortTypes { get; set; }

        /// <summary>
        /// IBatis排序条件
        /// </summary>
        public string IBatisOrderField
        {
            get
            {
                var sortstring = string.Empty;
                foreach (KeyValuePair<string, ESortType> pair in SortTypes)
                {
                    sortstring += string.Format("{0} {1},", pair.Key, pair.Value);
                }
                return sortstring.TrimEnd(',');
            }
        }

        public BasePagingSearchCondition()
        {
            TotalRecord = 0;
            CountMode = "";
            PageSize = 10;
            PageIndex = 1;
            SortTypes = new Dictionary<string, ESortType>();
        }

        /// <summary>
        ///（搜索实体转换为IBatis所识别的数据格式）
        ///注意：针对之前旧版本IBatis分页存储过程传递参数
        /// 最新方式支持搜索实体之间传递
        /// </summary>
        [NonSerialized]
        [Obsolete]
        public Func<Hashtable> MapHashtable;

        /// <summary>
        /// （搜索实体转换为Linq2Sql所识别的数据格式）
        /// 注意：针对linq where表达式（属性1==@0 and 属性2==@1 ）
        /// </summary>       
        [NonSerialized]
        public Func<KeyValuePair<string, object[]>> LinqWhereExpression;

        /// <summary>
        /// 针对linq2sql排序条件
        /// </summary>
        public Func<string> LinqOrderByExpression()
        {
            if (SortTypes == null || SortTypes.Count == 0)
            {
                //默认根据ID排序
                return () => { return "ID"; };
            }
            return () =>
            {
                var sortstring = string.Empty;
                foreach (KeyValuePair<string, ESortType> pair in SortTypes)
                {
                    sortstring += string.Format("{0} {1},", pair.Key, pair.Value);
                }
                return sortstring.TrimEnd(',');
            };
        }
    }

    /// <summary>
    /// 排序类型
    /// </summary>
    [Serializable]
    public enum ESortType
    {
        /// <summary>
        /// 升序
        /// </summary>
        Asc = 1,
        /// <summary>
        /// 降序
        /// </summary>
        Desc = 2
    }
}
